from flask import Blueprint, request, send_from_directory
import os
from service.transform_service.csv_service import CsvService

# 创建一个蓝图对象
upload_bp = Blueprint('upload', __name__)

# 设置 CSV 文件的保存路径
UPLOAD_FOLDER = 'file/csv_already_receive'
ALLOWED_EXTENSIONS = {'csv'}


# 检查文件扩展名是否允许
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@upload_bp.route('/upload', methods=['POST'])
def upload_file():
    if request.method == 'POST':
        # 检查是否有文件被上传
        if 'file' not in request.files:
            return "No file part"
        file = request.files['file']
        # 如果用户没有选择文件，则浏览器也会提交一个空的文件部分
        if file.filename == '':
            return "No selected file"
        if file and allowed_file(file.filename):
            # 保存文件到指定的文件夹
            filename = file.filename
            file.save(os.path.join(UPLOAD_FOLDER, filename))
            data_transform_service = CsvService()
            data_transform_service.load_data_from_csv(UPLOAD_FOLDER+'/'+filename)
            return f"File {filename} uploaded successfully."
        else:
            return "Invalid file format."


@upload_bp.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(UPLOAD_FOLDER,
                               filename)



